import { Component, ViewChild } from '@angular/core';
import { DataTableComponent, DialogService, TableWidthConfig } from '@devui';
import ledgerData from 'src/app/@core/data/mock-sales-ledger.json';
import { SalePaymentDetailComponent } from './sale-payment-detail/sale-payment-detail.component';
import { environment } from 'src/environments/environment';

export interface SalesPayment {
  salePaymentId: number;
  paymentNum: string;
  paymentDate: string; // ISO string
  customerID: number;
  customerName: string;
  customerShortName: string;
  customerContact: string;
  contactInfo: string;
  salesmanName: string;
  department: string;
  settlementMethod: string | null;
  paymentAccount: string | null;
  paymentType: string | null;
  receiptAmount: number;
  discountAmount: number;
  actualAmount: number;
  remainingAmount: number;
  remark: string;
  status: string;
  isConfirmed: boolean;
  creationDate: string;
  creator: string;
  confirmDate: string | null;
  confirmer: string | null;
  saleOrderNum: string;
  saleSettlementNum: string;
}

export interface SalesOrderRow {
  saleOrderId: number;
  saleOrderNum: string;
  orderDate: string; // yyyy-MM-dd HH:mm:ss
  customerOrderNum: string;
  customerName: string;
  deliveryDate: string;
  status: string;
  isClosed: boolean;
  creationDate: string;
  creator: string;
  customerShortName: string;
  customerContact: string;
  contactInfo: string;
  salesman: string;
  department: string;
  settlementCurrency: string; // 人民币
  settlementMethod: string | null;
  remark: string;
  totalQuantity: number;
  totalAmountWithTax: number;
  payments: SalesPayment[];
  // 运行时附加字段
  display?: boolean;
  receivableAmount?: number; // 应收金额（当前用订单含税金额代替）
  receivedAmount?: number; // 计算的：sum(actualAmount)
  unpaidAmount?: number;   // 计算的：totalAmountWithTax - receivedAmount
}

@Component({
  selector: 'app-sales-ledger',
  templateUrl: './sales-ledger.component.html',
  styleUrls: ['./sales-ledger.component.scss']
})
export class SalesLedgerComponent {
  // 基础数据与筛选
  tableData: SalesOrderRow[] = [];
  filteredData: SalesOrderRow[] = [];
  pageSizeOptions = [10, 20, 30, 50, 100];
  pager = { total: 0, pageIndex: 1, pageSize: 20 };
  // 查询条件
  orderNo: string = '';
  receiptNo: string = '';
  customerName: string = '';
  rangeDate: Date[] = [];

  @ViewChild(DataTableComponent, { static: true }) datatable!: DataTableComponent;
    constructor(private DialogService:DialogService) { }
  dataTableOptions = {
    columns: [
  { field: 'saleOrderNum', header: '单号', fieldType: 'text' },
  { field: 'customerName', header: '客户', fieldType: 'text' },
  { field: 'customerShortName', header: '客户简称', fieldType: 'text' },
  { field: 'orderDate', header: '下单日期', fieldType: 'text' },
  { field: 'deliveryDate', header: '交货日期', fieldType: 'text' },
  { field: 'totalAmountWithTax', header: '订单金额', fieldType: 'text' },
  { field: 'receivableAmount', header: '应收金额', fieldType: 'text' },
  { field: 'receivedAmount', header: '实收金额', fieldType: 'text' },
  { field: 'unpaidAmount', header: '未收金额', fieldType: 'text' },
  { field: 'status', header: '状态', fieldType: 'text' },
    ],
  };
  tableWidthConfig: TableWidthConfig[] = [
    { field: '操作', width: '72px' },
    { field: '打印', width: '72px' },
    { field: '单号', width: '220px' },
    { field: '客户', width: '220px' },
    { field: '客户简称', width: '150px' },
    { field: '下单日期', width: '160px' },
    { field: '交货日期', width: '160px' },
    { field: '订单金额', width: '160px' },
    { field: '应收金额', width: '160px' },
    { field: '实收金额', width: '150px' },
    { field: '未收金额', width: '150px' },
    { field: '状态', width: '120px' },
  ];
  ngOnInit(): void {
    // 初始化加载本地模拟数据，并计算已收/未收金额
    const items = (ledgerData as any).items as SalesOrderRow[];
    this.tableData = items.map((x) => {
      const received = (x.payments || []).reduce((s, p) => s + (p.actualAmount || 0), 0);
      const unpaid = Math.max((x.totalAmountWithTax || 0) - received, 0);
      const receivable = x.totalAmountWithTax || 0;
      return { ...x, display: false, receivableAmount: receivable, receivedAmount: received, unpaidAmount: unpaid };
    });
    this.applyFilterAndPaging();
  }
  // UI 交互
  toggleRowItem(rowItem: SalesOrderRow): void {
    rowItem.display = !rowItem.display;
  }
  // 过滤与分页
  rangeDateChange(event: Date[]) {
    this.rangeDate = event || [];
  }
  search(): void {
    this.pager.pageIndex = 1;
    this.applyFilterAndPaging();
  }
  reset(): void {
    this.orderNo = '';
    this.receiptNo = '';
    this.customerName = '';
    this.rangeDate = [];
    this.pager.pageIndex = 1;
    this.applyFilterAndPaging();
  }

  pageIndexChange(index: number) {
    this.pager.pageIndex = index;
    this.applyFilterAndPaging();
  }

  pageSizeChange(size: number) {
    this.pager.pageSize = size;
    this.pager.pageIndex = 1;
    this.applyFilterAndPaging();
  }

  private applyFilterAndPaging() {
    const all = [...this.tableData];
    // 过滤
    let list = all.filter((o) =>
      (!this.orderNo || o.saleOrderNum.includes(this.orderNo)) &&
      (!this.customerName || o.customerName.includes(this.customerName)) &&
      (!this.receiptNo || (o.payments || []).some((r) => r.paymentNum.includes(this.receiptNo)))
    );

    this.pager.total = list.length;

    // 分页
    const { pageIndex, pageSize } = this.pager;
    const begin = (pageIndex - 1) * pageSize;
    const endIndex = begin + pageSize;
    this.filteredData = list.slice(begin, endIndex);
  }

  // 汇总工具：统计收款单的 actualAmount
  sumPaymentActual(payments: SalesPayment[]): number {
    return (payments || []).reduce((s, r) => s + (r.actualAmount || 0), 0);
  }

  // 计算到某一笔（含自身）的累计实收
  cumulativeActual(payments: SalesPayment[], endIndexInclusive: number): number {
    if (!payments || endIndexInclusive == null) return 0;
    const end = Math.min(endIndexInclusive, payments.length - 1);
    let sum = 0;
    for (let i = 0; i <= end; i++) {
      sum += payments[i]?.actualAmount || 0;
    }
    return sum;
  }

  // 计算展开行中，某一笔之后的剩余未收（基于订单应收金额-累计已收）
  remainingAfter(row: SalesOrderRow, index: number): number {
    const receivable = row.receivableAmount || 0;
    const collected = this.cumulativeActual(row.payments || [], index);
    return Math.max(receivable - collected, 0);
  }

  // 整体汇总：剩余金额（订单应收 - 全部实收）
  groupRemaining(row: SalesOrderRow): number {
    const receivable = row.receivableAmount || 0;
    const collected = this.sumPaymentActual(row.payments || []);
    return Math.max(receivable - collected, 0);
  }

  // 整体汇总：收款是否完成（未收为 0 即完成）
  groupCompleted(row: SalesOrderRow): boolean {
    return (row.unpaidAmount || 0) <= 0;
  }

  private formatDate(d: Date) {
    const y = d.getFullYear();
    const m = (d.getMonth() + 1).toString().padStart(2, '0');
    const day = d.getDate().toString().padStart(2, '0');
    return `${y}-${m}-${day}`;
  }

  // 行内打印：订单行（改为按整单格式打印：订单信息 + 收款明细）
  printOrderRow(row: SalesOrderRow, ev?: Event): void {
    if (ev) { ev.stopPropagation(); ev.preventDefault(); }
    if (!row) return;
    const html = this.buildPrintHtml(row);
    this.printWithIframe(html);
  }

  // 行内打印：收款行
  printPaymentRow(item: SalesPayment, order: SalesOrderRow, ev?: Event): void {
    if (ev) { ev.stopPropagation(); ev.preventDefault(); }
    if (!item || !order) return;
    const idx = (order.payments || []).indexOf(item);
    const remaining = this.remainingAfter(order, Math.max(idx, 0));
    const html = this.buildPaymentRowHtml(item, order, remaining);
    this.printWithIframe(html);
  }

  // 旧：整单打印（保留以备后用）
  printCurrent(): void {
    const expanded = this.filteredData.find((x) => !!x.display);
    const target = expanded || this.filteredData[0];
    if (!target) {
      return;
    }
    const html = this.buildPrintHtml(target);
    this.printWithIframe(html);
  }

  private printWithIframe(html: string) {
    const iframe = document.createElement('iframe');
    iframe.style.position = 'fixed';
    iframe.style.right = '0';
    iframe.style.bottom = '0';
    iframe.style.width = '0';
    iframe.style.height = '0';
    iframe.style.border = '0';
    iframe.style.visibility = 'hidden';
    document.body.appendChild(iframe);

    const doc = iframe.contentDocument || iframe.contentWindow?.document;
    if (!doc) {
      document.body.removeChild(iframe);
      return;
    }
    doc.open();
    doc.write(html);
    doc.close();

    setTimeout(() => {
      try {
        iframe.contentWindow?.focus();
        iframe.contentWindow?.print();
      } finally {
        setTimeout(() => {
          if (iframe && iframe.parentNode) {
            iframe.parentNode.removeChild(iframe);
          }
        }, 400);
      }
    }, 200);
  }

  private to2(n: any): string {
    const x = Number(n);
    if (isNaN(x)) return '';
    return x.toLocaleString('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
  }

  private fmtDateStr(input: any, withTime = false): string {
    if (!input) return '';
    const d = new Date(input);
    if (isNaN(d.getTime())) return String(input);
    const y = d.getFullYear();
    const m = String(d.getMonth() + 1).padStart(2, '0');
    const da = String(d.getDate()).padStart(2, '0');
    if (!withTime) return `${y}-${m}-${da}`;
    const hh = String(d.getHours()).padStart(2, '0');
    const mm = String(d.getMinutes()).padStart(2, '0');
    return `${y}-${m}-${da} ${hh}:${mm}`;
  }

  // 打印模板：订单行（仅当前行字段）
  private buildOrderRowHtml(order: SalesOrderRow): string {
    const to2 = this.to2.bind(this);
    const now = this.fmtDateStr(new Date(), true);
    const style = `
      <style>
        @page { size: A4; margin: 12mm; }
        * { -webkit-print-color-adjust: exact; print-color-adjust: exact; }
        body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, 'Noto Sans', 'PingFang SC', 'Microsoft YaHei', sans-serif; }
        .sheet { width: 210mm; min-height: 297mm; margin: 0 auto; }
        .header { display: grid; grid-template-columns: 1fr auto; align-items: center; }
        .title { font-size: 20px; font-weight: 700; }
        .meta { font-size: 12px; color: #555; }
        table { width: 100%; border-collapse: collapse; margin-top: 8px; }
        th, td { border: 1px solid #333; padding: 6px 8px; font-size: 12px; }
        th { background: #f5f7fa; }
        tbody tr:nth-child(even) { background: #fafafa; }
        .num { text-align: right; }
      </style>
    `;
    const html = `<!DOCTYPE html><html lang="zh-CN"><head><meta charset="utf-8"/>${style}</head><body>
      <div class="sheet">
        <div class="header">
          <div class="title">销售台账 - 订单行</div>
          <div class="meta">打印时间：${now}</div>
        </div>
        <table>
          <thead>
            <tr>
              <th>单号</th>
              <th>客户</th>
              <th>客户简称</th>
              <th>下单日期</th>
              <th>交货日期</th>
              <th class="num">订单金额</th>
              <th class="num">应收金额</th>
              <th class="num">已收金额</th>
              <th class="num">未收金额</th>
              <th>状态</th>
            </tr>
          </thead>
          <tbody>
            <tr>
              <td>${order.saleOrderNum || ''}</td>
              <td>${order.customerName || ''}</td>
              <td>${order.customerShortName || ''}</td>
              <td>${this.fmtDateStr(order.orderDate, true)}</td>
              <td>${this.fmtDateStr(order.deliveryDate, true)}</td>
              <td class="num">${to2(order.totalAmountWithTax)}</td>
              <td class="num">${to2(order.receivableAmount)}</td>
              <td class="num">${to2(order.receivedAmount)}</td>
              <td class="num">${to2(order.unpaidAmount)}</td>
              <td>${order.status || ''}</td>
            </tr>
          </tbody>
        </table>
      </div>
    </body></html>`;
    return html;
  }

  // 打印模板：收款行（仅当前行字段）
  private buildPaymentRowHtml(item: SalesPayment, order: SalesOrderRow, remaining: number): string {
    const to2 = this.to2.bind(this);
    const now = this.fmtDateStr(new Date(), true);
    const style = `
      <style>
        @page { size: A4; margin: 12mm; }
        * { -webkit-print-color-adjust: exact; print-color-adjust: exact; }
        body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, 'Noto Sans', 'PingFang SC', 'Microsoft YaHei', sans-serif; }
        .sheet { width: 210mm; min-height: 297mm; margin: 0 auto; }
        .header { display: grid; grid-template-columns: 1fr auto; align-items: center; }
        .title { font-size: 20px; font-weight: 700; }
        .meta { font-size: 12px; color: #555; }
        .info { display: grid; grid-template-columns: repeat(2, 1fr); gap: 6px 24px; margin-top: 8px; font-size: 12px; }
        table { width: 100%; border-collapse: collapse; margin-top: 8px; }
        th, td { border: 1px solid #333; padding: 6px 8px; font-size: 12px; }
        th { background: #f5f7fa; }
        tbody tr:nth-child(even) { background: #fafafa; }
        .num { text-align: right; }
      </style>
    `;
    const html = `<!DOCTYPE html><html lang="zh-CN"><head><meta charset="utf-8"/>${style}</head><body>
      <div class="sheet">
        <div class="header">
          <div class="title">销售台账 - 收款行</div>
          <div class="meta">打印时间：${now}</div>
        </div>
        <div class="info">
          <div><strong>订单号：</strong>${order.saleOrderNum || ''}</div>
          <div><strong>客户：</strong>${order.customerName || ''}</div>
          <div><strong>订单金额：</strong>${to2(order.totalAmountWithTax)}</div>
          <div><strong>应收金额：</strong>${to2(order.receivableAmount)}</div>
        </div>
        <table>
          <thead>
            <tr>
              <th>收款单号</th>
              <th>收款日期</th>
              <th class="num">本笔实收</th>
              <th class="num">本笔后未收</th>
              <th>状态</th>
              <th>备注</th>
            </tr>
          </thead>
          <tbody>
            <tr>
              <td>${item.paymentNum || ''}</td>
              <td>${this.fmtDateStr(item.paymentDate, true)}</td>
              <td class="num">${to2(item.actualAmount)}</td>
              <td class="num">${to2(remaining)}</td>
              <td>${item.isConfirmed ? '已确认' : '未确认'}</td>
              <td>${item.remark || ''}</td>
            </tr>
          </tbody>
        </table>
      </div>
    </body></html>`;
    return html;
  }

  // 旧：整单打印模板（订单+收款明细）
  private buildPrintHtml(order: SalesOrderRow): string {
    const to2 = (n: any) => {
      const x = Number(n);
      if (isNaN(x)) return '';
      return x.toLocaleString('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
    };
    const now = this.fmtDateStr(new Date(), true);
    const sumActual = this.sumPaymentActual(order.payments || []);
    const count = (order.payments || []).length;
    const remaining = this.groupRemaining(order);

    const rows = (order.payments || []).map((p, i) => `
      <tr>
        <td>${i + 1}</td>
        <td>${p.paymentNum || ''}</td>
        <td>${this.fmtDateStr(p.paymentDate, true)}</td>
        <td class=\"num\">${to2(p.actualAmount)}</td>
        <td>${p.remark || ''}</td>
      </tr>
    `).join('');

    const style = `
      <style>
      @page { size: A4; margin: 10mm; }
      * { -webkit-print-color-adjust: exact; print-color-adjust: exact; }
      body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, 'Noto Sans', 'PingFang SC', 'Microsoft YaHei', sans-serif; }
      .sheet { width: 210mm; min-height: 297mm; padding: 10mm; margin: 0 auto; }
      .header { display: grid; grid-template-columns: 1fr auto; align-items: center; }
      .title { font-size: 22px; font-weight: 700; letter-spacing: 1px; }
      .meta { font-size: 12px; color: #555; }
      .info { display: grid; grid-template-columns: repeat(2, 1fr); gap: 6px 24px; font-size: 12px; margin-top: 6px; }
      table { width: 100%; border-collapse: collapse; margin-top: 10px; }
      th, td { border: 1px solid #333; padding: 6px 8px; font-size: 12px; }
      th { background: #f5f7fa; }
      tbody tr:nth-child(even) { background: #fafafa; }
      tr, td, th { page-break-inside: avoid; }
      .num { text-align: right; }
      tfoot td { font-weight: 700; }
      </style>
    `;

    const html = `<!DOCTYPE html><html lang=\"zh-CN\"><head><meta charset=\"utf-8\"/>${style}</head><body>
      <div class=\"sheet\">
        <div class=\"header\">
          <div class=\"title\">销售台账</div>
          <div class=\"meta\">打印时间：${now}</div>
        </div>
        <div class=\"info\">
          <div><strong>订单号：</strong>${order.saleOrderNum}</div>
          <div><strong>客户：</strong>${order.customerName}</div>
          <div><strong>下单日期：</strong>${this.fmtDateStr(order.orderDate, true)}</div>
          <div><strong>交货日期：</strong>${this.fmtDateStr(order.deliveryDate, true)}</div>
          <div><strong>订单金额：</strong>${to2(order.totalAmountWithTax)}</div>
          <div><strong>应收金额：</strong>${to2(order.receivableAmount)}</div>
          <div><strong>已收金额：</strong>${to2(order.receivedAmount)}</div>
          <div><strong>未收金额：</strong>${to2(order.unpaidAmount)}</div>
        </div>
        <table>
          <thead>
            <tr>
              <th style=\"width:44px;\">序</th>
              <th style=\"width:200px;\">收款单号</th>
              <th style=\"width:200px;\">收款日期</th>
              <th style=\"width:140px;\" class=\"num\">实收金额(元)</th>
              <th>备注</th>
            </tr>
          </thead>
          <tbody>
            ${rows || '<tr><td colspan=\"5\" style=\"text-align:center;\">无收款记录</td></tr>'}
          </tbody>
          <tfoot>
            <tr>
              <td colspan=\"2\">合计：${count} 笔</td>
              <td>—</td>
              <td class=\"num\">${to2(sumActual)}</td>
              <td>未收：${to2(remaining)}</td>
            </tr>
          </tfoot>
        </table>
      </div>
    </body></html>`;
    return html;
  }
  detail(payment?: SalesPayment, order?: SalesOrderRow) {
    const results = this.DialogService.open({
      id: 'sale-payment-detail',
      maxHeight: '70vh',
      width: '960px',
      backdropCloseable: true,
      data: { payment, order },
      title: '销售收款单',
      content: SalePaymentDetailComponent,
      onClose: () => {},
      buttons: [
        {
          cssClass: 'stress',
          text: '确定',
          handler: ($event: Event) => {
            results.modalInstance.hide();
          },
        },
        {
          id: 'btn-cancel',
          cssClass: 'common',
          text: '关闭',
          handler: ($event: Event) => {
            results.modalInstance.hide();
          },
        },
      ],
    });
  }
}
